package com.cskaoyan.service.wx.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.param.CommonData;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.bean.wx.WXOrderSubmitBo;
import com.cskaoyan.bean.wx.WXSubmitOrderVo;
import com.cskaoyan.bean.wxorder.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.wx.WXOrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : Caspar
 * @since : 2022.06.28 17:47
 */
@Service
public class WXOrderServiceImpl implements WXOrderService {

    @Autowired
    MarketOrderMapper marketOrderMapper;

    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;

    @Autowired
    MarketAddressMapper marketAddressMapper;

    @Autowired
    MarketCartMapper marketCartMapper;

    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    MarketSystemMapper marketSystemMapper;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    @Autowired
    MarketCommentMapper marketCommentMapper;

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    /**
     * 显示所有的订单信息
     *
     * @param showType
     * @param basePageInfo
     * @return com.cskaoyan.bean.param.CommonData<com.cskaoyan.bean.wxorder.WXOrderListVO>
     * @author: Caspar CXC
     * @since 2022/06/28 23:15
     */
    @Override
    public CommonData<WXOrderListVO> list(Integer showType, BasePageInfo basePageInfo, Integer userId) {

        List<WXOrderListVO> wxOrderListVOS = new ArrayList<>();

        // 准备获取订单
        MarketOrderExample example = new MarketOrderExample();
        MarketOrderExample.Criteria criteria1 = example.createCriteria();
        criteria1.andUserIdEqualTo(userId);

        // showType = 0 是所有订单
        // showType = 1 是待付款（未付款）订单
        // showType = 2 是待发货（已付款）订单
        // showType = 3 是待收货（已发货）订单
        // showType = 4 是待评价（已收货）订单
        if (showType == 1) {
            criteria1.andOrderStatusEqualTo((short) 101);
        } else if (showType == 2) {
            criteria1.andOrderStatusEqualTo((short) 201);
        } else if (showType == 3) {
            criteria1.andOrderStatusEqualTo((short) 301);
        } else if (showType == 4) {
            criteria1.andOrderStatusEqualTo((short) 401);

        }

        criteria1.andDeletedEqualTo(false);
        // 开启分页
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());

        // 根据用户id、订单状态获取订单
        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(example);

        for (int i = marketOrders.size() - 1; i >= 0; i--) {

            MarketOrder marketOrder = marketOrders.get(i);

            // for (MarketOrder marketOrder : marketOrders) {
            WXOrderListVO wxOrderListVO = new WXOrderListVO();

            Short orderStatus = marketOrder.getOrderStatus();

            WXOrderHandleOptionVO handleOptionVO = new WXOrderHandleOptionVO();

            // 设置回显相应的OrderStatusText、handleOption
            if (orderStatus == 101) {
                wxOrderListVO.setOrderStatusText("未付款");
                handleOptionVO.setCancel(true);
            } else if (orderStatus == 102) {
                wxOrderListVO.setOrderStatusText("用户取消");
                handleOptionVO.setDelete(true);
            } else if (orderStatus == 103) {
                wxOrderListVO.setOrderStatusText("系统取消");
                handleOptionVO.setDelete(true);
            } else if (orderStatus == 201) {
                wxOrderListVO.setOrderStatusText("已付款");
                handleOptionVO.setRefund(true);
            } else if (orderStatus == 202) {
                wxOrderListVO.setOrderStatusText("订单取消，退款中");
            } else if (orderStatus == 203) {
                wxOrderListVO.setOrderStatusText("已退款");
                handleOptionVO.setDelete(true);
            } else if (orderStatus == 301) {
                wxOrderListVO.setOrderStatusText("已发货");
                handleOptionVO.setConfirm(true);
            } else if (orderStatus == 401) {
                wxOrderListVO.setOrderStatusText("已收货");
                handleOptionVO.setAftersale(true);
                handleOptionVO.setComment(true);
                handleOptionVO.setDelete(true);
                handleOptionVO.setRebuy(true);
            } else if (orderStatus == 402) {
                wxOrderListVO.setOrderStatusText("系统自动收货");
            }

            wxOrderListVO.setAftersaleStatus(Integer.valueOf(marketOrder.getAftersaleStatus()));

            // 根据团购优惠是否为0，判断是否团购
            BigDecimal grouponPrice = marketOrder.getGrouponPrice();
            if (grouponPrice.compareTo(BigDecimal.valueOf(0)) != 0) {
                wxOrderListVO.setIsGroupin(true);
            } else {
                wxOrderListVO.setIsGroupin(false);
            }

            wxOrderListVO.setOrderSn(marketOrder.getOrderSn());
            wxOrderListVO.setActualPrice(marketOrder.getActualPrice());

            // 根据订单id，从market_order_goods表中取出商品信息，然后封装进GoodsList
            Integer orderId = marketOrder.getId();
            MarketOrderGoodsExample example1 = new MarketOrderGoodsExample();
            MarketOrderGoodsExample.Criteria criteria = example1.createCriteria();
            criteria.andOrderIdEqualTo(orderId);
            List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(example1);
            wxOrderListVO.setGoodsList(marketOrderGoods);

            wxOrderListVO.setId(orderId);
            wxOrderListVO.setHandleOption(handleOptionVO);

            wxOrderListVOS.add(wxOrderListVO);
        }

        // 这里是为了取出 total 和 pages
        PageInfo<MarketOrder> tempPageInfo = new PageInfo<>(marketOrders);

        PageInfo<WXOrderListVO> wxOrderListVOPageInfo = new PageInfo<>(wxOrderListVOS);

        CommonData data = CommonData.data(wxOrderListVOPageInfo);
        data.setTotal((int) tempPageInfo.getTotal());
        data.setPages(tempPageInfo.getPages());
        return data;
    }

    /**
     * 根据订单编号，显示单个订单详情信息
     *
     * @param orderId
     * @return com.cskaoyan.bean.wxorder.WXOrderDetailVO
     * @author: Caspar CXC
     * @since 2022/06/29 15:17
     */
    @Override
    public WXOrderDetailVO detail(Integer orderId) {

        WXOrderDetailVO wxOrderDetailVO = new WXOrderDetailVO();

        MarketOrderGoodsExample example = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> orderGoods = marketOrderGoodsMapper.selectByExample(example);

        wxOrderDetailVO.setExpressInfo(null);
        wxOrderDetailVO.setOrderGoods(orderGoods);

        // 根据订单id，拿到相应的订单
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        WXOrderDetailOrderInfoVO detailOrderInfoVO = new WXOrderDetailOrderInfoVO();

        // 得到快递的 编码 和 名字
        String shipChannel = marketOrder.getShipChannel();

        if (shipChannel != null) {
            detailOrderInfoVO.setExpCode(shipChannel);
            switch (shipChannel) {
                case "ZTO":
                    detailOrderInfoVO.setExpName("中通快递");
                    break;
                case "YTO":
                    detailOrderInfoVO.setExpName("圆通快递");
                    break;
                case "YD":
                    detailOrderInfoVO.setExpName("韵达快递");
                    break;
                case "YZPY":
                    detailOrderInfoVO.setExpName("邮政快递包裹");
                    break;
                case "EMS":
                    detailOrderInfoVO.setExpName("EMS");
                    break;
                case "DBL":
                    detailOrderInfoVO.setExpName("德邦快递");
                    break;
                case "FAST":
                    detailOrderInfoVO.setExpName("快捷快递");
                    break;
                case "ZJS":
                    detailOrderInfoVO.setExpName("宅急送");
                    break;
                case "TNT":
                    detailOrderInfoVO.setExpName("TNT快递");
                    break;
                case "UPS":
                    detailOrderInfoVO.setExpName("UPS");
                    break;
                case "DHL":
                    detailOrderInfoVO.setExpName("DHL");
                    break;
                case "FEDEX":
                    detailOrderInfoVO.setExpName("FEDEX联邦(国内件)");
                    break;
                case "FEDEX_GJ":
                    detailOrderInfoVO.setExpName("FEDEX联邦(国际件)");
                    break;
                default:
                    detailOrderInfoVO.setExpName(null);
                    break;
            }
        }

        detailOrderInfoVO.setConsignee(marketOrder.getConsignee());
        detailOrderInfoVO.setAddress(marketOrder.getAddress());
        detailOrderInfoVO.setAddTime(marketOrder.getAddTime());
        detailOrderInfoVO.setOrderSn(marketOrder.getOrderSn());
        detailOrderInfoVO.setActualPrice(marketOrder.getActualPrice());
        detailOrderInfoVO.setMobile(marketOrder.getMobile());
        detailOrderInfoVO.setMessage(marketOrder.getMessage());
        detailOrderInfoVO.setAftersaleStatus(marketOrder.getAftersaleStatus());
        detailOrderInfoVO.setGoodsPrice(marketOrder.getGoodsPrice());
        detailOrderInfoVO.setExpNo(marketOrder.getShipSn());
        detailOrderInfoVO.setCouponPrice(marketOrder.getCouponPrice());
        detailOrderInfoVO.setId(marketOrder.getId());
        detailOrderInfoVO.setFreightPrice(marketOrder.getFreightPrice());

        WXOrderHandleOptionVO handleOptionVO = new WXOrderHandleOptionVO();

        Short orderStatus = marketOrder.getOrderStatus();
        if (orderStatus == 101) {
            detailOrderInfoVO.setOrderStatusText("未付款");
            handleOptionVO.setCancel(true);
            handleOptionVO.setPay(true);
        } else if (orderStatus == 102) {
            detailOrderInfoVO.setOrderStatusText("用户取消");
            handleOptionVO.setDelete(true);
        } else if (orderStatus == 103) {
            detailOrderInfoVO.setOrderStatusText("系统取消");
            handleOptionVO.setDelete(true);
        } else if (orderStatus == 201) {
            detailOrderInfoVO.setOrderStatusText("已付款");
            handleOptionVO.setRefund(true);
        } else if (orderStatus == 202) {
            detailOrderInfoVO.setOrderStatusText("订单取消，退款中");
        } else if (orderStatus == 203) {
            detailOrderInfoVO.setOrderStatusText("已退款");
            handleOptionVO.setDelete(true);
        } else if (orderStatus == 301) {
            detailOrderInfoVO.setOrderStatusText("已发货");
            handleOptionVO.setConfirm(true);
        } else if (orderStatus == 401) {
            detailOrderInfoVO.setOrderStatusText("已收货");
            handleOptionVO.setAftersale(true);
            handleOptionVO.setComment(true);
            handleOptionVO.setDelete(true);
            handleOptionVO.setRebuy(true);
        }
        detailOrderInfoVO.setHandleOption(handleOptionVO);

        wxOrderDetailVO.setOrderInfo(detailOrderInfoVO);
        return wxOrderDetailVO;
    }

    /**
     * 通过订单id，用户取消订单
     *
     * @param orderId
     * @return void
     * @author: Caspar CXC
     * @since 2022/06/29 20:47
     */
    @Override
    public void cancel(Integer orderId) {
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        // 更改订单状态为102（用户取消）
        marketOrder.setOrderStatus((short) 102);

        marketOrder.setUpdateTime(new Date());
        marketOrder.setEndTime(new Date());
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    @Transactional
    public BaseRespVo prepay(Integer orderId) {
        MarketOrder order = new MarketOrder();
        order.setId(orderId);
        order.setOrderStatus((short) 201);
        order.setUpdateTime(new Date());
        order.setPayTime(new Date());
        marketOrderMapper.updateByPrimaryKeySelective(order);
        return BaseRespVo.ok();
    }

    /**
     * 通过订单id，用户申请退款
     *
     * @param orderId
     * @return void
     * @author: Caspar CXC
     * @since 2022/06/28 21:03
     */
    @Override
    public void refund(Integer orderId) {
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);

        // 更改订单状态为202（申请退款）
        marketOrder.setOrderStatus((short) 202);

        marketOrder.setUpdateTime(new Date());
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    /**
     * 通过订单id，用户删除订单
     *
     * @param orderId
     * @return void
     * @author: Caspar CXC
     * @since 2022/06/28 20:45
     */
    @Override
    public void delete(Integer orderId) {
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        marketOrder.setDeleted(true);
        marketOrder.setUpdateTime(new Date());
        marketOrder.setEndTime(new Date());
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    /**
     * 通过订单id，用户确认收货
     *
     * @param orderId
     * @return void
     * @author: Caspar CXC
     * @since 2022/06/28 20:24
     */
    @Override
    public void confirm(Integer orderId) {

        // 查询这个订单有几种商品，每种商品需要评价一次
        MarketOrderGoodsExample example = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(example);
        int count = marketOrderGoods.size();

        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);

        // 更改订单状态为401（用户收货）
        marketOrder.setOrderStatus((short) 401);
        marketOrder.setConfirmTime(new Date());
        marketOrder.setUpdateTime(new Date());
        marketOrder.setComments((short) count);
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }


    /**
     * 准备评论时触发的接口，从 market_order_goods 表中返回订单的相信信息
     *
     * @param orderId
     * @param goodsId
     * @return com.cskaoyan.bean.MarketOrderGoods
     * @author: Caspar CXC
     * @since 2022/06/29 17:04
     */
    @Override
    public MarketOrderGoods goods(Integer orderId, Integer goodsId) {

        MarketOrderGoodsExample example = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        criteria.andGoodsIdEqualTo(goodsId);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(example);

        // 这里通过订单编号和商品编号拿到商品详情，在market_order_goods表中，同时满足条件的只有一条信息
        MarketOrderGoods marketOrderGood = marketOrderGoods.get(0);

        return marketOrderGood;
    }

    /**
     * 发布对商品进行评论的信息
     *
     * @param wxOrderCommentPO
     * @return void
     * @author: Caspar CXC
     * @since 2022/06/29 17:26
     */
    @Override
    public void comment(WXOrderCommentPO wxOrderCommentPO, Integer userId) {

        /*
        商品的评论是逐个评论，

        使用MarketCommentMapper完成评论
        评论后，market_order表中的comment的数量-1，
        market_order_goods表中的comment设为commentId

        订单结束时间要更新
         */

        Integer orderGoodsId = wxOrderCommentPO.getOrderGoodsId();
        MarketOrderGoods marketOrderGoods = marketOrderGoodsMapper.selectByPrimaryKey(orderGoodsId);

        MarketComment marketComment = new MarketComment();
        marketComment.setValueId(marketOrderGoods.getGoodsId());
        marketComment.setType((byte) 0);
        marketComment.setContent(wxOrderCommentPO.getContent());
        marketComment.setUserId(userId);
        if (wxOrderCommentPO.getPicUrls().length != 0) {
            marketComment.setHasPicture(true);
            marketComment.setPicUrls(wxOrderCommentPO.getPicUrls());
        } else {
            marketComment.setHasPicture(false);
            marketComment.setPicUrls(wxOrderCommentPO.getPicUrls());
        }
        marketComment.setStar(wxOrderCommentPO.getStar());
        marketComment.setAddTime(new Date());
        marketComment.setDeleted(false);
        marketCommentMapper.insert(marketComment);

        // 得到评论的id
        Integer commentId = marketComment.getId();

        // 订单商品评论，如果是-1，则超期不能评价；如果是0，则可以评价；如果其他值，则是comment表里面的评论ID
        // 评论后，market_order表中的comment的数量-1，更新时间
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(marketOrderGoods.getOrderId());
        Short comments = marketOrder.getComments();
        comments = (short) (comments - 1);
        marketOrder.setComments(comments);
        marketOrder.setUpdateTime(new Date());
        marketOrder.setEndTime(new Date());
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);

        // market_order_goods表中的comment设为commentId
        // 当market_order_goods表中的comment不为0，则没有评价按钮
        marketOrderGoods.setComment(commentId);
        marketOrderGoods.setUpdateTime(new Date());
        marketOrderGoodsMapper.updateByPrimaryKeySelective(marketOrderGoods);

    }

    /**
     * 此方法用于提交订单
     *
     * @param wxOrderSubmitBo
     * @return com.cskaoyan.bean.BaseRespVo
     * @author Can
     * @since 2022/06/29 19:39
     */
    @Transactional
    @Override
    public BaseRespVo submitOrder(WXOrderSubmitBo wxOrderSubmitBo) {

        // 用户id
        Subject subject = SecurityUtils.getSubject();
        MarketUser principal = (MarketUser) subject.getPrincipal();
        if (principal == null) {
            return BaseRespVo.error(501, "需要登录");
        }
        Integer userId = principal.getId();

        // 先根据 userId 和 checked = 1 到购物车表找到全部商品
        MarketCartExample cartExample = new MarketCartExample();

        MarketCartExample.Criteria cartCriteria = cartExample.createCriteria().andDeletedEqualTo(false).andUserIdEqualTo(userId).andCheckedEqualTo(true);
        if (wxOrderSubmitBo.getCartId() != 0) {
            cartCriteria.andIdEqualTo(wxOrderSubmitBo.getCartId());
        }
        // 用户购物车里的所有数据
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(cartExample);

        if (ObjectUtils.isEmpty(marketCarts)) {
            return BaseRespVo.error(401, "已下单");
        }

        // 用户地址表里的全部数据
        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(wxOrderSubmitBo.getAddressId());

        // 用户优惠券
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(wxOrderSubmitBo.getCouponId());

        // 所有产品id
        List<Integer> productIds = new ArrayList<>();

        for (MarketCart marketCart : marketCarts) {
            Integer productId = marketCart.getProductId();
            productIds.add(productId);
        }

        MarketGoodsProductExample productExample = new MarketGoodsProductExample();
        productExample.createCriteria().andDeletedEqualTo(false).andIdIn(productIds);

        // 用户购物车里的所有产品数据
        List<MarketGoodsProduct> products = marketGoodsProductMapper.selectByExample(productExample);

        // 为了方便比较产品库存 按照产品id进行排序
        List<MarketCart> cartList = marketCarts.stream().sorted(Comparator.comparing(MarketCart::getProductId)).collect(Collectors.toList());
        List<MarketGoodsProduct> productList = products.stream().sorted(Comparator.comparing(MarketGoodsProduct::getId)).collect(Collectors.toList());

        // 判断产品的数量 能否 符合下单成功 每件产品都需要判断  marketCarts的size等于products的size
        for (int i = 0; i < cartList.size(); i++) {
            // 库存不足 返回
            if (cartList.get(i).getNumber() > productList.get(i).getNumber()) {
                return BaseRespVo.error(710, "库存不足！");
            }
            // 库存充足 修改产品的数量
            MarketGoodsProduct product = new MarketGoodsProduct();
            product.setId(cartList.get(i).getProductId());
            product.setNumber(productList.get(i).getNumber() - cartList.get(i).getNumber());
            marketGoodsProductMapper.updateByPrimaryKeySelective(product);
        }

        // 删除用户购物车里的下单产品
        marketCartMapper.deleteByExample(cartExample);

        // 不需要付运费的金额下限 达到后免去运费
        MarketSystem freight_min = marketSystemMapper.selectByPrimaryKey(6);

        // 运费
        MarketSystem freight_value = marketSystemMapper.selectByPrimaryKey(8);

        // 生成订单编码  前8位是日期 后6位随机数字
        // 判断订单号是否重复
        String orderSn = getOrderSn();
        while (marketOrderMapper.selectByOrderSn(orderSn) != null) {
            orderSn = getOrderSn();
        }

        // 优惠券减免
        BigDecimal couponPrice = BigDecimal.ZERO;
        if (marketCoupon != null) {
            couponPrice = marketCoupon.getDiscount();
        }

        // 用户积分减免
        BigDecimal integralPrice = new BigDecimal(0);
        // 团购优惠价减免
        BigDecimal grouponPrice = new BigDecimal(0);
        // 运费
        BigDecimal freightPrice = new BigDecimal(freight_value.getKeyValue());

        // 商品总费用
        BigDecimal goodsPrice = BigDecimal.ZERO;
        for (MarketCart marketCart : cartList) {
            goodsPrice = goodsPrice.add(marketCart.getPrice().multiply(BigDecimal.valueOf(marketCart.getNumber())));
        }

        // 订单费用
        BigDecimal orderPrice;
        if (goodsPrice.compareTo(new BigDecimal(freight_min.getKeyValue())) < 0) {
            orderPrice = goodsPrice.add(freightPrice).subtract(couponPrice);
        } else {
            orderPrice = goodsPrice.subtract(couponPrice);
        }

        // 实付费用
        BigDecimal actualPrice = orderPrice.subtract(integralPrice);

        // 先插入订单表
        MarketOrder order = new MarketOrder();
        order.setUserId(userId);
        order.setOrderSn(orderSn);
        order.setOrderStatus((short) 101);
        order.setConsignee(marketAddress.getName());
        order.setMobile(marketAddress.getTel());
        order.setAddress(marketAddress.getProvince() + marketAddress.getCity() + marketAddress.getCounty() + marketAddress.getAddressDetail());
        order.setMessage(wxOrderSubmitBo.getMessage());
        order.setGoodsPrice(goodsPrice);
        if (goodsPrice.compareTo(new BigDecimal(freight_min.getKeyValue())) < 0) {
            order.setFreightPrice(freightPrice);
        } else {
            order.setFreightPrice(BigDecimal.ZERO);
        }
        order.setCouponPrice(couponPrice);
        order.setIntegralPrice(integralPrice);
        order.setGrouponPrice(grouponPrice);
        order.setOrderPrice(orderPrice);
        order.setActualPrice(actualPrice);
        order.setAddTime(new Date());
        order.setUpdateTime(new Date());
        order.setDeleted(false);

        marketOrderMapper.insertSelective(order);

        // 更新用户的优惠券状态
        if (marketCoupon != null) {
            // 同一优惠券可能有多个 选一个更新状态
            MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
            couponUserExample.createCriteria().andUserIdEqualTo(userId).andCouponIdEqualTo(marketCoupon.getId()).andStatusEqualTo((short) 0);
            List<MarketCouponUser> couponUserList = marketCouponUserMapper.selectByExample(couponUserExample);
            Integer couponUserId = couponUserList.get(0).getId();

            MarketCouponUser couponUser = new MarketCouponUser();
            couponUser.setId(couponUserId);
            couponUser.setOrderId(order.getId());
            couponUser.setStatus((short) 1);
            couponUser.setUsedTime(new Date());
            couponUser.setUpdateTime(new Date());
            marketCouponUserMapper.updateByPrimaryKeySelective(couponUser);
        }

        // 在插入订单和商品的关系表
        // 多个产品 插入多条数据
        List<MarketOrderGoods> marketOrderGoodsList = new ArrayList<>();
        for (MarketCart marketCart : cartList) {
            MarketOrderGoods orderGoods = new MarketOrderGoods();
            orderGoods.setOrderId(order.getId());
            orderGoods.setGoodsId(marketCart.getGoodsId());
            orderGoods.setGoodsName(marketCart.getGoodsName());
            orderGoods.setGoodsSn(marketCart.getGoodsSn());
            orderGoods.setProductId(marketCart.getProductId());
            orderGoods.setNumber(marketCart.getNumber());
            orderGoods.setPrice(marketCart.getPrice());
            orderGoods.setSpecifications(marketCart.getSpecifications());
            orderGoods.setPicUrl(marketCart.getPicUrl());
            orderGoods.setComment(0);
            orderGoods.setAddTime(marketCart.getAddTime());
            orderGoods.setUpdateTime(marketCart.getUpdateTime());
            orderGoods.setDeleted(false);
            marketOrderGoodsList.add(orderGoods);
        }
        marketOrderGoodsMapper.insertOrderGoodsList(marketOrderGoodsList);


        WXSubmitOrderVo orderVo = new WXSubmitOrderVo();
        orderVo.setOrderId(order.getId());
        orderVo.setGrouponLinkId(wxOrderSubmitBo.getGrouponLinkId());
        return BaseRespVo.ok(orderVo);
    }

    /**
     * 用于生成订单编号
     *
     * @return java.lang.String
     * @author Can
     * @since 2022/06/30 9:34
     */
    private String getOrderSn() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String format = dateFormat.format(new Date());
        StringBuffer stringBuffer = new StringBuffer("");
        for (int i = 0; i < 6; i++) {
            int anInt = new Random().nextInt(10);
            stringBuffer.append(anInt);
        }
        String orderSn = format + stringBuffer.toString();
        return orderSn;
    }
}
